package com.zz.nondatain.view.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.zz.nondatain.base.BaseActivity;
import com.zz.nondatain.databinding.ActivityActiveSignInBinding;
import com.zz.nondatain.service.LocationService;
import com.zz.nondatain.view.activity.AnnouncementActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 主动签到页面
 */
public class ActiveSignInActivity extends BaseActivity<ActivityActiveSignInBinding> {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    private Timer timer;
    private BroadcastReceiver locationReceiver;


    /**
     * 初始化视图
     */
    @Override
    protected void initView() {
        // 设置今天的日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String today = dateFormat.format(new Date());
        binding.tvDate.setText(today);
        
        // 定时更新当前时间
        updateCurrentTime();
        // 初始化监听器
        initListener();
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        // 注册位置广播接收器
        locationReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.zz.nondatain.LOCATION_UPDATE".equals(intent.getAction())) {
                    String location = intent.getStringExtra("location");
                    if (location != null) {
                        binding.tvLocation.setText(location);
                    }
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("com.zz.nondatain.LOCATION_UPDATE");
        registerReceiver(locationReceiver, filter);
        
        // 启动定位服务
        startLocationService();
    }

    @Override
    protected void initObservers() {
        // 不需要观察者，保持空实现
    }

    @Override
    protected ActivityActiveSignInBinding getViewBinding() {
        return ActivityActiveSignInBinding.inflate(getLayoutInflater());
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        // 设置返回按钮点击事件
        binding.btnBack.setOnClickListener(v -> finish());
        
        // 设置"我的"按钮点击事件
        binding.btnMy.setOnClickListener(v -> {
            // 跳转到我的签到页面
            Intent intent = new Intent(this, MySignInActivity.class);
            startActivity(intent);
        });



        // 设置选项点击事件
        binding.rbForgetCheckIn.setOnClickListener(v -> updateReasonText("忘记打卡"));
        binding.rbLeave.setOnClickListener(v -> updateReasonText("请假"));
        binding.rbRequestActiveSignIn.setOnClickListener(v -> updateReasonText("要求主动签到"));
        binding.rbCannotCheckIn.setOnClickListener(v -> updateReasonText("无法打卡"));

        // 设置"重新定位"按钮点击事件
        binding.btnRefreshLocation.setOnClickListener(v -> {
            showToast("正在重新定位...");
            startLocationService();
        });

        // 设置主动签到按钮点击事件
        binding.btnActiveSignIn.setOnClickListener(v -> {
            // 执行签到操作
            String reason = binding.etReason.getText().toString().trim();
            if (reason.isEmpty()) {
                showToast("请选择或输入签到原因");
                return;
            }
            
            // 这里可以添加签到逻辑...
            showToast("签到成功!");
            finish(); // 签到完成后关闭页面
        });
    }

    /**
     * 更新输入框文本
     */
    private void updateReasonText(String reason) {
        binding.etReason.setText(reason);
    }

    /**
     * 更新当前时间并启动定时器
     */
    private void updateCurrentTime() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
                    String currentTime = timeFormat.format(new Date());
                    binding.tvCurrentTime.setText(currentTime);
                });
            }
        }, 0, 1000);
    }

    /**
     * 启动定位服务
     */
    private void startLocationService() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            Intent intent = new Intent(this, LocationService.class);
            startService(intent);
        }
    }

    /**
     * 权限请求结果处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocationService();
            } else {
                showToast("未获得定位权限，无法使用定位功能");
            }
        }
    }

    /**
     * 显示Toast消息
     */
    protected void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理定时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        
        // 注销广播接收器
        if (locationReceiver != null) {
            unregisterReceiver(locationReceiver);
            locationReceiver = null;
        }
        
        // 停止定位服务
        Intent intent = new Intent(this, LocationService.class);
        stopService(intent);
    }
} 